#include "TcpServer.hpp"
#include "Calculate.hpp"
#include "ProTocol.hpp"
#include <iostream>
#include <memory>
#include <unistd.h>

using namespace Net_Work;
using namespace CalculateNs;
using namespace Protocol;

// 处理报文  返回值为响应对象
std::string HandlerRequest(std::string &inbufferstream, bool *error_code)
{
    *error_code = true;
    // 构建计算对象
    Calculate calculate;
    // 构建响应对象 提取inbufferstream中的respuest信息
    std::unique_ptr<Factory> factory = std::make_unique<Factory>();
    std::shared_ptr<Request> req = factory->BuildRequest(); // 要填充的请求数据

    // 报文处理
    std::string total_resp_string; // 响应的字符串数据
    std::string message;           // 请求的字符串数据
    while(Decode(inbufferstream ,&message))
    {
        std::cout << message << "------- message" << std::endl;

        // 填充请求数据
        if(!req->Deserialize(message))
        {
            std::cout << "Deserialize error" << std::endl;
            *error_code = false;
            return std::string();
        }
        std::cout << "Deserialize success" << std::endl;

        // 处理请求数据
        std::shared_ptr<Protocol::Response> resp = calculate.Cal(req);

        std::cout << "处理请求数据成功" << std::endl;
        // 序列化
        std::string send_string;
        resp->Serialize(&send_string);
        // 添加报文
        send_string = Encode(send_string);

        std::cout << "返回的响应" << send_string << std::endl;
        total_resp_string += send_string;
    }   
    return total_resp_string;
}

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " port" << std::endl;
        return 0;
    }
    uint16_t localport = std::stoi(argv[1]);

    std::unique_ptr<TcpServer> svr(new TcpServer(localport, HandlerRequest));

    svr->Loop();

    return 0;
}